package com.suyl.designpattern;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RemoveAllProfile {

    @Test
    public void test() {
        // 构建 大 list 60w
        long a = System.currentTimeMillis();
        List src = new ArrayList(600001);
        for (int i = 0; i < 600000; i++) {
            src.add(i);
        }
        // 构建 大 list 6w
        long b = System.currentTimeMillis();
        List oth = new ArrayList(60001);
        for (int i = 0; i < 600000; i++) {
            if (i % 10 == 1) {
                oth.add(i);
            }
        }
        long c = System.currentTimeMillis();
        List result = removeAll(src, oth); // 高效方法
        long d = System.currentTimeMillis();

        System.out.println(b - a + "ms src" + src.size() + "个");
        System.out.println(c - b + "ms oth" + oth.size() + "个");
        System.out.println(d - c + "ms result" + result.size() + "个");

        List res = new ArrayList();
        src.removeAll(oth); // 使用自带 removeAll普通方法
        long e = System.currentTimeMillis();
        System.out.println(e - d + "ms res" + src.size() + "个");
    }

    /**
     * 高效方法
     *
     * @param src
     * @param oth
     * @return
     */
    public static List removeAll(List src, List oth) {

        LinkedList result = new LinkedList(src); // 大集合用 LinkedList
        HashSet othHash = new HashSet(oth);  // 小集合用 HashSet

        Iterator iterator = result.iterator(); // 采用Iterator迭代器进行数据操作

        while (iterator.hasNext()) {
            if (othHash.contains(iterator.next())) {
                iterator.remove();
            }
        }
        return result;
    }
}
